package pl.edu.agh.agents.gui.actions;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JDialog;
import javax.swing.JSlider;
import javax.swing.JTextField;

import pl.edu.agh.agents.generator.Generator;

public class GenerateAction extends AbstractAction {
	private static final long serialVersionUID = 1416422056403961231L;
	private JTextField filenameField;
	private JTextField statesField;
	private JTextField agentsField;
	private JSlider densitySlider;
	private JDialog dialog;

	public GenerateAction(String name, JTextField filenameField, JTextField statesField, JTextField agentsField, JSlider densitySlider, JDialog dialog) {
		super(name);

		this.filenameField = filenameField;
		this.statesField = statesField;
		this.agentsField = agentsField;
		this.densitySlider = densitySlider;
		this.dialog = dialog;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		String filename = filenameField.getText();
		String states = statesField.getText();
		String agents = agentsField.getText();
		String density = String.valueOf(densitySlider.getValue());

		try {
			int nStates = Integer.parseInt(states);
			int nAgents = Integer.parseInt(agents);
			int nDensity = densitySlider.getValue();
			if (filename.isEmpty() 
					||  nStates < 0 
					|| nAgents < 0
					|| nAgents >= nStates
					|| nDensity <= 0
					|| nDensity > 100) {
				System.err.println("Invalid parameters");
				return;
			}
		}
		catch (NumberFormatException e) {
			System.err.println("Invalid parameters");
			return;
		}

		String[] args = {filename, states, agents, density};

		Generator.main(args);

		dialog.setVisible(false);
	}
}